<template>
  <div class="stories-container">
    <el-card shadow="hover" class="story-card">
      <template #header>
        <div class="card-header">
          <span class="title">助农故事</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon> 新增故事
          </el-button>
        </div>
      </template>

      <el-table :data="storiesList" border style="width: 100%" v-loading="loading" class="story-table">
        <el-table-column prop="title" label="标题" width="250" />
        <el-table-column prop="content" label="内容摘要" width="300" :show-overflow-tooltip="true" />
        <el-table-column prop="viewCount" label="浏览次数" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="dialogVisible" :title="storyForm.id ? '编辑助农故事' : '新增助农故事'" width="50%">
        <el-form :model="storyForm" :rules="rules" ref="storyFormRef" label-width="100px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="storyForm.title" placeholder="请输入标题" clearable />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input
                v-model="storyForm.content"
                type="textarea"
                placeholder="请输入内容"
                clearable
                :rows="5"
            />
          </el-form-item>
          <el-form-item label="封面图片">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :http-request="customImageUpload"
            >
              <div class="avatar-wrapper">
                <img
                    v-if="storyForm.image"
                    :src="storyForm.image"
                    class="avatar-image"
                />
                <div v-else class="avatar-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <span class="upload-text">上传封面图片</span>
                </div>
                <div class="upload-mask">
                  <el-icon class="upload-icon"><Edit /></el-icon>
                  <span class="upload-text">更换图片</span>
                </div>
              </div>
              <div class="mt-2 text-sm text-gray-500">建议尺寸：800x450像素，格式：JPG/PNG</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="视频文件">
            <el-upload
                class="video-uploader"
                :show-file-list="false"
                :before-upload="beforeVideoUpload"
                :http-request="customVideoUpload"
            >
              <div v-if="storyForm.video" class="video-preview">
                <video controls class="video-preview-player">
                  <source :src="storyForm.video" type="video/mp4">
                  您的浏览器不支持视频播放
                </video>
                <div class="video-overlay">
                  <el-icon class="video-icon"><VideoPlay /></el-icon>
                  <span class="video-text">点击更换视频</span>
                </div>
              </div>
              <div v-else class="video-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <span class="upload-text">上传视频文件</span>
              </div>
              <div class="mt-2 text-sm text-gray-500">支持格式：MP4，最大500MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="浏览次数" prop="viewCount">
            <el-input-number v-model.number="storyForm.viewCount" :min="0" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, VideoPlay } from '@element-plus/icons-vue'

// 从localStorage获取用户信息
const userStr = localStorage.getItem('admin')
const user = userStr ? JSON.parse(userStr) : null

const storiesList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const storyForm = ref({
  id: null,
  title: '',
  content: '',
  video: '',
  image: '',
  viewCount: 0
})
const rules = {
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在3到50个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '内容不能为空', trigger: 'blur' }
  ],
  viewCount: [
    { type: 'number', min: 0, message: '浏览次数必须大于等于0', trigger: 'blur' }
  ]
}
const storyFormRef = ref(null)

const fetchStories = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${BASE_URL}/api/v1/government/private/sel`)
    storiesList.value = response.data.data
  } catch (error) {
    console.error('获取助农故事失败:', error)
    ElMessage.error('获取助农故事失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  storyForm.value = {
    id: null,
    title: '',
    content: '',
    video: '',
    image: '',
    viewCount: 0
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  storyForm.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (rowData) => {
  try {
    await ElMessageBox.confirm('确定要删除这条助农故事吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.post(`${BASE_URL}/api/v1/government/private/deleteVideo`, {
      videoId: rowData.id
    })

    ElMessage.success('删除成功')
    fetchStories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除助农故事失败:', error)
      ElMessage.error('删除助农故事失败')
    }
  }
}

const submitForm = async () => {
  try {
    await storyFormRef.value.validate()
    const payload = { ...storyForm.value }

    // 确保viewCount是数字类型
    if (typeof payload.viewCount === 'string') {
      payload.viewCount = parseInt(payload.viewCount, 10)
    }

    let response
    if (payload.id) {
      response = await axios.post(`${BASE_URL}/api/v1/government/private/updateVideo`, payload)
    } else {
      response = await axios.post(`${BASE_URL}/api/v1/government/private/addVideo`, payload)
    }

    if (response.data.code === 2000) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchStories()
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('保存助农故事失败:', error)
      ElMessage.error('保存助农故事失败')
    }
  }
}

// 图片上传相关
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }

  return true
}

const customImageUpload = async (options) => {
  const { file } = options
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', user?.id || '123')

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    })

    if (response.data.code === 2000) {
      storyForm.value.image = response.data.data
    } else {
      throw new Error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败: ' + error.message)
    throw error
  }
}

// 视频上传相关
const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt500M = file.size / 1024 / 1024 < 500

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!')
    return false
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过500MB!')
    return false
  }

  return true
}

const customVideoUpload = async (options) => {
  const { file } = options
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', user?.id || '123')

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    })

    if (response.data.code === 2000) {
      storyForm.value.video = response.data.data
    } else {
      throw new Error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('视频上传失败: ' + error.message)
    throw error
  }
}

onMounted(() => {
  fetchStories()
})
</script>

<style scoped>
.stories-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.story-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.story-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

/* 图片上传样式 */
.avatar-uploader {
  --el-avatar-size: 178px;
}

.avatar-wrapper {
  position: relative;
  width: var(--el-avatar-size);
  height: var(--el-avatar-size);
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

/* 视频上传样式 */
.video-uploader {
  width: 100%;
  max-width: 400px;
}

.video-preview {
  position: relative;
  width: 100%;
  height: 225px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.video-preview-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.video-preview:hover .video-overlay {
  opacity: 1;
}

.video-icon {
  font-size: 36px;
  margin-bottom: 12px;
}

.video-text {
  font-size: 16px;
}

.video-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 225px;
  color: #8c939d;
  background-color: #f5f7fa;
  border-radius: 6px;
  border: 1px dashed var(--el-border-color);
}

.mt-2 {
  margin-top: 0.5rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.text-gray-500 {
  color: #6b7280;
}
</style>